

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/xiazhimiao.ico">
  <link rel="icon" href="/img/xiazhimiao.ico">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="XiaZhiMiao">
  <meta name="keywords" content="">
  
    <meta name="description" content="1. Redis入门1.1 Redis简介Redis是一个基于内存的key-value结构数据库。Redis 是互联网技术领域使用最为广泛的存储中间件。 官网：https:&#x2F;&#x2F;redis.io中文网：https:&#x2F;&#x2F;www.redis.net.cn&#x2F; key-value结构存储：   主要特点：  基于内存存储，读写性能高   适合存储热点数据（热点商品、资讯、新闻） 企业应用广泛  Redis是">
<meta property="og:type" content="article">
<meta property="og:title" content="Redis入门">
<meta property="og:url" content="https://xiazhimiao.gitee.io/2024/08/11/Redis%E5%85%A5%E9%97%A8/index.html">
<meta property="og:site_name" content="瀚海无江">
<meta property="og:description" content="1. Redis入门1.1 Redis简介Redis是一个基于内存的key-value结构数据库。Redis 是互联网技术领域使用最为广泛的存储中间件。 官网：https:&#x2F;&#x2F;redis.io中文网：https:&#x2F;&#x2F;www.redis.net.cn&#x2F; key-value结构存储：   主要特点：  基于内存存储，读写性能高   适合存储热点数据（热点商品、资讯、新闻） 企业应用广泛  Redis是">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://xiazhimiao.gitee.io/2024/08/11/Redis%E5%85%A5%E9%97%A8/image-20221130173459174.png">
<meta property="og:image" content="https://xiazhimiao.gitee.io/2024/08/11/Redis%E5%85%A5%E9%97%A8/image-20221130180657152.png">
<meta property="og:image" content="https://xiazhimiao.gitee.io/2024/08/11/Redis%E5%85%A5%E9%97%A8/image-20221130181950351.png">
<meta property="og:image" content="https://xiazhimiao.gitee.io/2024/08/11/Redis%E5%85%A5%E9%97%A8/image-20221130182207020.png">
<meta property="og:image" content="https://xiazhimiao.gitee.io/2024/08/11/Redis%E5%85%A5%E9%97%A8/image-20221130183253539.png">
<meta property="og:image" content="https://xiazhimiao.gitee.io/java%E5%AD%A6%E4%B9%A0%E8%B7%AF%E5%BE%84%E9%BB%91%E9%A9%AC%E8%B5%84%E6%96%99/%E8%8B%8D%E7%A9%B9%E5%A4%96%E5%8D%96/1%E3%80%81%E9%BB%91%E9%A9%AC%E7%A8%8B%E5%BA%8F%E5%91%98Java%E9%A1%B9%E7%9B%AE%E3%80%8A%E8%8B%8D%E7%A9%B9%E5%A4%96%E5%8D%96%E3%80%8B%E4%BC%81%E4%B8%9A%E7%BA%A7%E5%BC%80%E5%8F%91%E5%AE%9E%E6%88%98/%E8%AE%B2%E4%B9%89/%E8%AE%B2%E4%B9%89/day05/assets/image-20221130183746355.png">
<meta property="og:image" content="https://xiazhimiao.gitee.io/2024/08/11/Redis%E5%85%A5%E9%97%A8/image-20221130192210418.png">
<meta property="og:image" content="https://xiazhimiao.gitee.io/2024/08/11/Redis%E5%85%A5%E9%97%A8/image-20221130192310916.png">
<meta property="og:image" content="https://xiazhimiao.gitee.io/2024/08/11/Redis%E5%85%A5%E9%97%A8/image-20221130190150749.png">
<meta property="og:image" content="https://xiazhimiao.gitee.io/2024/08/11/Redis%E5%85%A5%E9%97%A8/image-20221130193121969.png">
<meta property="og:image" content="https://xiazhimiao.gitee.io/2024/08/11/Redis%E5%85%A5%E9%97%A8/image-20221130193332666.png">
<meta property="og:image" content="https://xiazhimiao.gitee.io/2024/08/11/Redis%E5%85%A5%E9%97%A8/image-20221130193532735.png">
<meta property="og:image" content="https://xiazhimiao.gitee.io/2024/08/11/Redis%E5%85%A5%E9%97%A8/image-20221130193951036.png">
<meta property="og:image" content="https://xiazhimiao.gitee.io/2024/08/11/Redis%E5%85%A5%E9%97%A8/image-20210927143741458.png">
<meta property="og:image" content="https://xiazhimiao.gitee.io/2024/08/11/Redis%E5%85%A5%E9%97%A8/image-20221130205351403.png">
<meta property="article:published_time" content="2024-08-10T23:02:01.000Z">
<meta property="article:modified_time" content="2024-08-10T23:13:17.557Z">
<meta property="article:author" content="XiaZhiMiao">
<meta property="article:tag" content="黑马">
<meta property="article:tag" content="Redis">
<meta property="article:tag" content="redis">
<meta property="article:tag" content="入门">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://xiazhimiao.gitee.io/2024/08/11/Redis%E5%85%A5%E9%97%A8/image-20221130173459174.png">
  
  
  
  <title>Redis入门 - 瀚海无江</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"xiazhimiao.gitee.io","root":"/","version":"1.9.7","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"follow_dnt":false,"baidu":null,"google":{"measurement_id":null},"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":"Gwfs4a7ZrcziUqDRNGWYCyFE-gzGzoHsz","app_key":"EftcChyXDAcaoX5XepM4iOMI","server_url":null,"path":"window.location.pathname","ignore_local":true}},"search_path":"/local-search.xml","include_content_in_search":true};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  

  

  
    <!-- Google tag (gtag.js) -->
    <script async>
      if (!Fluid.ctx.dnt) {
        Fluid.utils.createScript("https://www.googletagmanager.com/gtag/js?id=", function() {
          window.dataLayer = window.dataLayer || [];
          function gtag() {
            dataLayer.push(arguments);
          }
          gtag('js', new Date());
          gtag('config', '');
        });
      }
    </script>
  

  

  

  

  
    
  



  
<meta name="generator" content="Hexo 7.3.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>瀚海无江，思心似雪</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/" target="_self">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/" target="_self">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/" target="_self">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/" target="_self">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/" target="_self">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/bj/1.jpg') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="Redis入门"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        XiaZhiMiao
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2024-08-11 07:02" pubdate>
          2024年8月11日 早上
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          2.9k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          25 分钟
        
      </span>
    

    
    
      
        <span id="leancloud-page-views-container" class="post-meta" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="leancloud-page-views"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <h1 id="seo-header">Redis入门</h1>
            
            
              <div class="markdown-body">
                
                <h2 id="1-Redis入门"><a href="#1-Redis入门" class="headerlink" title="1. Redis入门"></a>1. Redis入门</h2><h3 id="1-1-Redis简介"><a href="#1-1-Redis简介" class="headerlink" title="1.1 Redis简介"></a>1.1 Redis简介</h3><p>Redis是一个基于<strong>内存</strong>的key-value结构数据库。Redis 是互联网技术领域使用最为广泛的<strong>存储中间件</strong>。</p>
<p><strong>官网：</strong><a target="_blank" rel="noopener" href="https://redis.io/">https://redis.io</a><br><strong>中文网：</strong><a target="_blank" rel="noopener" href="https://www.redis.net.cn/">https://www.redis.net.cn/</a></p>
<p><strong>key-value结构存储：</strong></p>
<img src="/2024/08/11/Redis%E5%85%A5%E9%97%A8/image-20221130173459174.png" srcset="/img/loading.gif" lazyload class="" title="image-20221130173459174">

<p><strong>主要特点：</strong></p>
<ul>
<li>基于内存存储，读写性能高  </li>
<li>适合存储热点数据（热点商品、资讯、新闻）</li>
<li>企业应用广泛</li>
</ul>
<p>Redis是用C语言开发的一个开源的高性能键值对(key-value)数据库，官方提供的数据是可以达到100000+的QPS（每秒内查询次数）。它存储的value类型比较丰富，也被称为结构化的NoSql数据库。</p>
<p>NoSql（Not Only SQL），不仅仅是SQL，泛指<strong>非关系型数据库</strong>。NoSql数据库并不是要取代关系型数据库，而是关系型数据库的补充。</p>
<p><strong>关系型数据库(RDBMS)：</strong></p>
<ul>
<li>Mysql</li>
<li>Oracle</li>
<li>DB2</li>
<li>SQLServer</li>
</ul>
<p><strong>非关系型数据库(NoSql)：</strong></p>
<ul>
<li>Redis</li>
<li>Mongo db</li>
<li>MemCached</li>
</ul>
<h3 id="1-2-Redis下载与安装"><a href="#1-2-Redis下载与安装" class="headerlink" title="1.2 Redis下载与安装"></a>1.2 Redis下载与安装</h3><h4 id="1-2-1-Redis下载"><a href="#1-2-1-Redis下载" class="headerlink" title="1.2.1 Redis下载"></a>1.2.1 Redis下载</h4><p>Redis安装包分为windows版和Linux版：</p>
<ul>
<li>Windows版下载地址：<a target="_blank" rel="noopener" href="https://github.com/microsoftarchive/redis/releases">https://github.com/microsoftarchive/redis/releases</a></li>
<li>Linux版下载地址： <a target="_blank" rel="noopener" href="https://download.redis.io/releases/">https://download.redis.io/releases/</a></li>
</ul>
<h4 id="1-2-2-Redis安装"><a href="#1-2-2-Redis安装" class="headerlink" title="1.2.2 Redis安装"></a>1.2.2 Redis安装</h4><p><strong>1）在Windows中安装Redis(项目中使用)</strong></p>
<p>Redis的Windows版属于绿色软件，直接解压即可使用，解压后目录结构如下：</p>
<style>.qcmjrwqoudfl{zoom:50%;}</style><img src="/2024/08/11/Redis%E5%85%A5%E9%97%A8/image-20221130180657152.png" srcset="/img/loading.gif" lazyload class="qcmjrwqoudfl" alt="image-20221130180657152">

<p><strong>2）在Linux中安装Redis(简单了解)</strong></p>
<p>在Linux系统安装Redis步骤：</p>
<ol>
<li>将Redis安装包上传到Linux</li>
<li>解压安装包，命令：tar -zxvf redis-4.0.0.tar.gz -C &#x2F;usr&#x2F;local</li>
<li>安装Redis的依赖环境gcc，命令：yum install gcc-c++</li>
<li>进入&#x2F;usr&#x2F;local&#x2F;redis-4.0.0，进行编译，命令：make</li>
<li>进入redis的src目录进行安装，命令：make install</li>
</ol>
<p>安装后重点文件说明：</p>
<ul>
<li>&#x2F;usr&#x2F;local&#x2F;redis-4.0.0&#x2F;src&#x2F;redis-server：Redis服务启动脚本</li>
<li>&#x2F;usr&#x2F;local&#x2F;redis-4.0.0&#x2F;src&#x2F;redis-cli：Redis客户端脚本</li>
<li>&#x2F;usr&#x2F;local&#x2F;redis-4.0.0&#x2F;redis.conf：Redis配置文件</li>
</ul>
<h3 id="1-3-Redis服务启动与停止"><a href="#1-3-Redis服务启动与停止" class="headerlink" title="1.3 Redis服务启动与停止"></a>1.3 Redis服务启动与停止</h3><p>以window版Redis进行演示：</p>
<h4 id="1-3-1-服务启动命令"><a href="#1-3-1-服务启动命令" class="headerlink" title="1.3.1 服务启动命令"></a>1.3.1 服务启动命令</h4><p><strong>redis-server.exe redis.windows.conf</strong></p>
<style>.mtdthwucwcvp{zoom:50%;}</style><img src="/2024/08/11/Redis%E5%85%A5%E9%97%A8/image-20221130181950351.png" srcset="/img/loading.gif" lazyload class="mtdthwucwcvp" alt="image-20221130181950351">

<p>Redis服务默认端口号为 <strong>6379</strong> ，通过快捷键<strong>Ctrl + C</strong> 即可停止Redis服务</p>
<p>当Redis服务启动成功后，可通过客户端进行连接。</p>
<h4 id="1-3-2-客户端连接命令"><a href="#1-3-2-客户端连接命令" class="headerlink" title="1.3.2 客户端连接命令"></a>1.3.2 客户端连接命令</h4><p><strong>redis-cli.exe</strong></p>
<style>.bfbmusnlzfty{zoom:50%;}</style><img src="/2024/08/11/Redis%E5%85%A5%E9%97%A8/image-20221130182207020.png" srcset="/img/loading.gif" lazyload class="bfbmusnlzfty" alt="image-20221130182207020">

<p>通过redis-cli.exe命令默认连接的是本地的redis服务，并且使用默认6379端口。也可以通过指定如下参数连接：</p>
<ul>
<li>-h ip地址</li>
<li>-p 端口号</li>
<li>-a 密码（如果需要）</li>
</ul>
<h4 id="1-3-3-修改Redis配置文件"><a href="#1-3-3-修改Redis配置文件" class="headerlink" title="1.3.3 修改Redis配置文件"></a>1.3.3 修改Redis配置文件</h4><p>设置Redis服务密码，修改redis.windows.conf</p>
<figure class="highlight apache"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs apache"><span class="hljs-attribute">requirepass</span> <span class="hljs-number">123456</span><br></code></pre></td></tr></table></figure>

<p><strong>注意：</strong></p>
<ul>
<li>修改密码后需要重启Redis服务才能生效</li>
<li>Redis配置文件中 # 表示注释</li>
</ul>
<p>重启Redis后，再次连接Redis时，需加上密码，否则连接失败。</p>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs stylus">redis-cli<span class="hljs-selector-class">.exe</span> -h localhost -<span class="hljs-selector-tag">p</span> <span class="hljs-number">6379</span> -<span class="hljs-selector-tag">a</span> <span class="hljs-number">123456</span><br></code></pre></td></tr></table></figure>

<style>.vvynntnclgjz{zoom:50%;}</style><img src="/2024/08/11/Redis%E5%85%A5%E9%97%A8/image-20221130183253539.png" srcset="/img/loading.gif" lazyload class="vvynntnclgjz" alt="image-20221130183253539">

<p>此时，-h 和 -p 参数可省略不写。</p>
<h4 id="1-3-4-Redis客户端图形工具"><a href="#1-3-4-Redis客户端图形工具" class="headerlink" title="1.3.4 Redis客户端图形工具"></a>1.3.4 Redis客户端图形工具</h4><p>默认提供的客户端连接工具界面不太友好，同时操作也较为麻烦，接下来，引入一个Redis客户端图形工具。</p>
<p>在当天资料中已提供安装包，直接安装即可。</p>
<img src="../../../../java学习路径黑马资料/苍穹外卖/1、黑马程序员Java项目《苍穹外卖》企业级开发实战/讲义/讲义/day05/assets/image-20221130183746355.png" srcset="/img/loading.gif" lazyload alt="image-20221130183746355" style="zoom:50%;" /> 

<p>安装完毕后，直接双击启动</p>
<p><strong>新建连接</strong></p>
<style>.msschnmctdya{zoom:33%;}</style><img src="/2024/08/11/Redis%E5%85%A5%E9%97%A8/image-20221130192210418.png" srcset="/img/loading.gif" lazyload class="msschnmctdya" alt="image-20221130192210418">

<p><strong>连接成功</strong></p>
<style>.bjlmxkgimibj{zoom:33%;}</style><img src="/2024/08/11/Redis%E5%85%A5%E9%97%A8/image-20221130192310916.png" srcset="/img/loading.gif" lazyload class="bjlmxkgimibj" alt="image-20221130192310916">

<h2 id="2-Redis数据类型"><a href="#2-Redis数据类型" class="headerlink" title="2. Redis数据类型"></a>2. Redis数据类型</h2><h3 id="2-1-五种常用数据类型介绍"><a href="#2-1-五种常用数据类型介绍" class="headerlink" title="2.1 五种常用数据类型介绍"></a>2.1 五种常用数据类型介绍</h3><p>Redis存储的是key-value结构的数据，其中key是字符串类型，value有5种常用的数据类型：</p>
<ul>
<li>字符串 string</li>
<li>哈希 hash</li>
<li>列表 list</li>
<li>集合 set</li>
<li>有序集合 sorted set &#x2F; zset</li>
</ul>
<h3 id="2-2-各种数据类型特点"><a href="#2-2-各种数据类型特点" class="headerlink" title="2.2 各种数据类型特点"></a>2.2 各种数据类型特点</h3><style>.sfhgegbtburp{zoom:50%;}</style><img src="/2024/08/11/Redis%E5%85%A5%E9%97%A8/image-20221130190150749.png" srcset="/img/loading.gif" lazyload class="sfhgegbtburp" alt="image-20221130190150749">

<p><strong>解释说明：</strong></p>
<ul>
<li>字符串(string)：普通字符串，Redis中最简单的数据类型</li>
<li>哈希(hash)：也叫散列，类似于Java中的HashMap结构</li>
<li>列表(list)：按照插入顺序排序，可以有重复元素，类似于Java中的LinkedList</li>
<li>集合(set)：无序集合，没有重复元素，类似于Java中的HashSet</li>
<li>有序集合(sorted set&#x2F;zset)：集合中每个元素关联一个分数(score)，根据分数升序排序，没有重复元素</li>
</ul>
<h2 id="3-Redis常用命令"><a href="#3-Redis常用命令" class="headerlink" title="3. Redis常用命令"></a>3. Redis常用命令</h2><h3 id="3-1-字符串操作命令"><a href="#3-1-字符串操作命令" class="headerlink" title="3.1 字符串操作命令"></a>3.1 字符串操作命令</h3><p>Redis 中字符串类型常用命令：</p>
<ul>
<li><strong>SET</strong> key value 					         设置指定key的值</li>
<li><strong>GET</strong> key                                        获取指定key的值</li>
<li><strong>SETEX</strong> key seconds value         设置指定key的值，并将 key 的过期时间设为 seconds 秒</li>
<li><strong>SETNX</strong> key value                        只有在 key    不存在时设置 key 的值</li>
</ul>
<p>更多命令可以参考Redis中文网：<a target="_blank" rel="noopener" href="https://www.redis.net.cn/">https://www.redis.net.cn</a></p>
<h3 id="3-2-哈希操作命令"><a href="#3-2-哈希操作命令" class="headerlink" title="3.2 哈希操作命令"></a>3.2 哈希操作命令</h3><p>Redis hash 是一个string类型的 field 和 value 的映射表，hash特别适合用于存储对象，常用命令：</p>
<ul>
<li><strong>HSET</strong> key field value             将哈希表 key 中的字段 field 的值设为 value</li>
<li><strong>HGET</strong> key field                       获取存储在哈希表中指定字段的值</li>
<li><strong>HDEL</strong> key field                       删除存储在哈希表中的指定字段</li>
<li><strong>HKEYS</strong> key                              获取哈希表中所有字段</li>
<li><strong>HVALS</strong> key                              获取哈希表中所有值</li>
</ul>
<style>.mhwqnejncljg{zoom:67%;}</style><img src="/2024/08/11/Redis%E5%85%A5%E9%97%A8/image-20221130193121969.png" srcset="/img/loading.gif" lazyload class="mhwqnejncljg" alt="image-20221130193121969">

<h3 id="3-3-列表操作命令"><a href="#3-3-列表操作命令" class="headerlink" title="3.3 列表操作命令"></a>3.3 列表操作命令</h3><p>Redis 列表是简单的字符串列表，按照插入顺序排序，常用命令：</p>
<ul>
<li><strong>LPUSH</strong> key value1 [value2]         将一个或多个值插入到列表头部</li>
<li><strong>LRANGE</strong> key start stop                获取列表指定范围内的元素</li>
<li><strong>RPOP</strong> key                                       移除并获取列表最后一个元素</li>
<li><strong>LLEN</strong> key                                        获取列表长度</li>
<li><strong>BRPOP</strong> key1 [key2 ] timeout       移出并获取列表的最后一个元素， 如果列表没有元素会阻塞列表直到等待超    时或发现可弹出元素为止</li>
</ul>
<style>.weqkieefnmju{zoom:67%;}</style><img src="/2024/08/11/Redis%E5%85%A5%E9%97%A8/image-20221130193332666.png" srcset="/img/loading.gif" lazyload class="weqkieefnmju" alt="image-20221130193332666">

<h3 id="3-4-集合操作命令"><a href="#3-4-集合操作命令" class="headerlink" title="3.4 集合操作命令"></a>3.4 集合操作命令</h3><p>Redis set 是string类型的无序集合。集合成员是唯一的，这就意味着集合中不能出现重复的数据，常用命令：</p>
<ul>
<li><strong>SADD</strong> key member1 [member2]            向集合添加一个或多个成员</li>
<li><strong>SMEMBERS</strong> key                                         返回集合中的所有成员</li>
<li><strong>SCARD</strong> key                                                  获取集合的成员数</li>
<li><strong>SINTER</strong> key1 [key2]                                   返回给定所有集合的交集</li>
<li><strong>SUNION</strong> key1 [key2]                                 返回所有给定集合的并集</li>
<li><strong>SREM</strong> key member1 [member2]            移除集合中一个或多个成员</li>
</ul>
<style>.rsssynehohjr{zoom:67%;}</style><img src="/2024/08/11/Redis%E5%85%A5%E9%97%A8/image-20221130193532735.png" srcset="/img/loading.gif" lazyload class="rsssynehohjr" alt="image-20221130193532735">

<h3 id="3-5-有序集合操作命令"><a href="#3-5-有序集合操作命令" class="headerlink" title="3.5 有序集合操作命令"></a>3.5 有序集合操作命令</h3><p>Redis有序集合是string类型元素的集合，且不允许有重复成员。每个元素都会关联一个double类型的分数。常用命令：</p>
<p>常用命令：</p>
<ul>
<li><strong>ZADD</strong> key score1 member1 [score2 member2]     向有序集合添加一个或多个成员</li>
<li><strong>ZRANGE</strong> key start stop [WITHSCORES]                     通过索引区间返回有序集合中指定区间内的成员</li>
<li><strong>ZINCRBY</strong> key increment member                              有序集合中对指定成员的分数加上增量 increment</li>
<li><strong>ZREM</strong> key member [member …]                                移除有序集合中的一个或多个成员</li>
</ul>
<style>.bnxkppjmwfry{zoom:67%;}</style><img src="/2024/08/11/Redis%E5%85%A5%E9%97%A8/image-20221130193951036.png" srcset="/img/loading.gif" lazyload class="bnxkppjmwfry" alt="image-20221130193951036">

<h3 id="3-6-通用命令"><a href="#3-6-通用命令" class="headerlink" title="3.6 通用命令"></a>3.6 通用命令</h3><p>Redis的通用命令是不分数据类型的，都可以使用的命令：</p>
<ul>
<li>KEYS pattern 		查找所有符合给定模式( pattern)的 key </li>
<li>EXISTS key 		检查给定 key 是否存在</li>
<li>TYPE key 		返回 key 所储存的值的类型</li>
<li>DEL key 		该命令用于在 key 存在是删除 key</li>
</ul>
<h2 id="4-在Java中操作Redis"><a href="#4-在Java中操作Redis" class="headerlink" title="4.在Java中操作Redis"></a>4.在Java中操作Redis</h2><h3 id="4-1-Redis的Java客户端"><a href="#4-1-Redis的Java客户端" class="headerlink" title="4.1 Redis的Java客户端"></a>4.1 Redis的Java客户端</h3><p>前面我们讲解了Redis的常用命令，这些命令是我们操作Redis的基础，那么我们在java程序中应该如何操作Redis呢？这就需要使用Redis的Java客户端，就如同我们使用JDBC操作MySQL数据库一样。</p>
<p>Redis 的 Java 客户端很多，常用的几种：</p>
<ul>
<li>Jedis</li>
<li>Lettuce</li>
<li>Spring Data Redis</li>
</ul>
<p>Spring 对 Redis 客户端进行了整合，提供了 Spring Data Redis，在Spring Boot项目中还提供了对应的Starter，即 spring-boot-starter-data-redis。</p>
<p>我们重点学习<strong>Spring Data Redis</strong>。</p>
<h3 id="4-2-Spring-Data-Redis使用方式"><a href="#4-2-Spring-Data-Redis使用方式" class="headerlink" title="4.2 Spring Data Redis使用方式"></a>4.2 Spring Data Redis使用方式</h3><h4 id="4-2-1-介绍"><a href="#4-2-1-介绍" class="headerlink" title="4.2.1 介绍"></a>4.2.1 介绍</h4><p>Spring Data Redis 是 Spring 的一部分，提供了在 Spring 应用中通过简单的配置就可以访问 Redis 服务，对 Redis 底层开发包进行了高度封装。在 Spring 项目中，可以使用Spring Data Redis来简化 Redis 操作。</p>
<p>网址：<a target="_blank" rel="noopener" href="https://spring.io/projects/spring-data-redis">https://spring.io/projects/spring-data-redis</a></p>
<style>.mnuhigxtklmj{zoom:33%;}</style><img src="/2024/08/11/Redis%E5%85%A5%E9%97%A8/image-20210927143741458.png" srcset="/img/loading.gif" lazyload class="mnuhigxtklmj" alt="image-20210927143741458">

<p>Spring Boot提供了对应的Starter，maven坐标：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>	<span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>	<span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-data-redis<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br></code></pre></td></tr></table></figure>

<p>Spring Data Redis中提供了一个高度封装的类：<strong>RedisTemplate</strong>，对相关api进行了归类封装,将同一类型操作封装为operation接口，具体分类如下：</p>
<ul>
<li>ValueOperations：string数据操作</li>
<li>SetOperations：set类型数据操作</li>
<li>ZSetOperations：zset类型数据操作</li>
<li>HashOperations：hash类型的数据操作</li>
<li>ListOperations：list类型的数据操作</li>
</ul>
<h4 id="4-2-2-环境搭建"><a href="#4-2-2-环境搭建" class="headerlink" title="4.2.2 环境搭建"></a>4.2.2 环境搭建</h4><p>进入到sky-server模块</p>
<p><strong>1). 导入Spring Data Redis的maven坐标(已完成)</strong></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span><br>     <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.boot<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span><br>     <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-boot-starter-data-redis<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span><br></code></pre></td></tr></table></figure>



<p><strong>2). 配置Redis数据源</strong></p>
<p>在application-dev.yml中添加</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs yaml"><span class="hljs-attr">sky:</span><br>  <span class="hljs-attr">redis:</span><br>    <span class="hljs-attr">host:</span> <span class="hljs-string">localhost</span><br>    <span class="hljs-attr">port:</span> <span class="hljs-number">6379</span><br>    <span class="hljs-attr">password:</span> <span class="hljs-number">123456</span><br>    <span class="hljs-attr">database:</span> <span class="hljs-number">10</span><br></code></pre></td></tr></table></figure>

<p><strong>解释说明：</strong></p>
<p>database:指定使用Redis的哪个数据库，Redis服务启动后默认有16个数据库，编号分别是从0到15。</p>
<p>可以通过修改Redis配置文件来指定数据库的数量。</p>
<p>在application.yml中添加读取application-dev.yml中的相关Redis配置</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs yaml"><span class="hljs-attr">spring:</span><br>  <span class="hljs-attr">profiles:</span><br>    <span class="hljs-attr">active:</span> <span class="hljs-string">dev</span><br>  <span class="hljs-attr">redis:</span><br>    <span class="hljs-attr">host:</span> <span class="hljs-string">$&#123;sky.redis.host&#125;</span><br>    <span class="hljs-attr">port:</span> <span class="hljs-string">$&#123;sky.redis.port&#125;</span><br>    <span class="hljs-attr">password:</span> <span class="hljs-string">$&#123;sky.redis.password&#125;</span><br>    <span class="hljs-attr">database:</span> <span class="hljs-string">$&#123;sky.redis.database&#125;</span><br></code></pre></td></tr></table></figure>



<p><strong>3). 编写配置类，创建RedisTemplate对象</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.sky.config;<br><br><span class="hljs-keyword">import</span> lombok.extern.slf4j.Slf4j;<br><span class="hljs-keyword">import</span> org.springframework.context.annotation.Bean;<br><span class="hljs-keyword">import</span> org.springframework.context.annotation.Configuration;<br><span class="hljs-keyword">import</span> org.springframework.data.redis.connection.RedisConnectionFactory;<br><span class="hljs-keyword">import</span> org.springframework.data.redis.core.RedisTemplate;<br><span class="hljs-keyword">import</span> org.springframework.data.redis.serializer.StringRedisSerializer;<br><br><span class="hljs-meta">@Configuration</span><br><span class="hljs-meta">@Slf4j</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">RedisConfiguration</span> &#123;<br><br>    <span class="hljs-meta">@Bean</span><br>    <span class="hljs-keyword">public</span> RedisTemplate <span class="hljs-title function_">redisTemplate</span><span class="hljs-params">(RedisConnectionFactory redisConnectionFactory)</span>&#123;<br>        log.info(<span class="hljs-string">&quot;开始创建redis模板对象...&quot;</span>);<br>        <span class="hljs-type">RedisTemplate</span> <span class="hljs-variable">redisTemplate</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RedisTemplate</span>();<br>        <span class="hljs-comment">//设置redis的连接工厂对象</span><br>        redisTemplate.setConnectionFactory(redisConnectionFactory);<br>        <span class="hljs-comment">//设置redis key的序列化器</span><br>        redisTemplate.setKeySerializer(<span class="hljs-keyword">new</span> <span class="hljs-title class_">StringRedisSerializer</span>());<br>        <span class="hljs-keyword">return</span> redisTemplate;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><strong>解释说明：</strong></p>
<p>当前配置类不是必须的，因为 Spring Boot 框架会自动装配 RedisTemplate 对象，但是默认的key序列化器为</p>
<p>JdkSerializationRedisSerializer，导致我们存到Redis中后的数据和原始数据有差别，故设置为</p>
<p>StringRedisSerializer序列化器。</p>
<p><strong>4). 通过RedisTemplate对象操作Redis</strong></p>
<p>在test下新建测试类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.sky.test;<br><br><span class="hljs-keyword">import</span> org.junit.jupiter.api.Test;<br><span class="hljs-keyword">import</span> org.springframework.beans.factory.annotation.Autowired;<br><span class="hljs-keyword">import</span> org.springframework.boot.test.context.SpringBootTest;<br><span class="hljs-keyword">import</span> org.springframework.data.redis.core.*;<br><br><span class="hljs-meta">@SpringBootTest</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">SpringDataRedisTest</span> &#123;<br>    <span class="hljs-meta">@Autowired</span><br>    <span class="hljs-keyword">private</span> RedisTemplate redisTemplate;<br><br>    <span class="hljs-meta">@Test</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">testRedisTemplate</span><span class="hljs-params">()</span>&#123;<br>        System.out.println(redisTemplate);<br>        <span class="hljs-comment">//string数据操作</span><br>        <span class="hljs-type">ValueOperations</span> <span class="hljs-variable">valueOperations</span> <span class="hljs-operator">=</span> redisTemplate.opsForValue();<br>        <span class="hljs-comment">//hash类型的数据操作</span><br>        <span class="hljs-type">HashOperations</span> <span class="hljs-variable">hashOperations</span> <span class="hljs-operator">=</span> redisTemplate.opsForHash();<br>        <span class="hljs-comment">//list类型的数据操作</span><br>        <span class="hljs-type">ListOperations</span> <span class="hljs-variable">listOperations</span> <span class="hljs-operator">=</span> redisTemplate.opsForList();<br>        <span class="hljs-comment">//set类型数据操作</span><br>        <span class="hljs-type">SetOperations</span> <span class="hljs-variable">setOperations</span> <span class="hljs-operator">=</span> redisTemplate.opsForSet();<br>        <span class="hljs-comment">//zset类型数据操作</span><br>        <span class="hljs-type">ZSetOperations</span> <span class="hljs-variable">zSetOperations</span> <span class="hljs-operator">=</span> redisTemplate.opsForZSet();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>测试：</p>
<style>.mqytxdfwqrfl{zoom:50%;}</style><img src="/2024/08/11/Redis%E5%85%A5%E9%97%A8/image-20221130205351403.png" srcset="/img/loading.gif" lazyload class="mqytxdfwqrfl" alt="image-20221130205351403">

<p>说明RedisTemplate对象注入成功，并且通过该RedisTemplate对象获取操作5种数据类型相关对象。</p>
<p>上述环境搭建完毕后，接下来，我们就来具体对常见5种数据类型进行操作。</p>
<h4 id="4-2-3-操作常见类型数据"><a href="#4-2-3-操作常见类型数据" class="headerlink" title="4.2.3 操作常见类型数据"></a>4.2.3 操作常见类型数据</h4><p><strong>1). 操作字符串类型数据</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">    * 操作字符串类型的数据</span><br><span class="hljs-comment">    */</span><br>   <span class="hljs-meta">@Test</span><br>   <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">testString</span><span class="hljs-params">()</span>&#123;<br>       <span class="hljs-comment">// set get setex setnx</span><br>       redisTemplate.opsForValue().set(<span class="hljs-string">&quot;name&quot;</span>,<span class="hljs-string">&quot;小明&quot;</span>);<br>       <span class="hljs-type">String</span> <span class="hljs-variable">city</span> <span class="hljs-operator">=</span> (String) redisTemplate.opsForValue().get(<span class="hljs-string">&quot;name&quot;</span>);<br>       System.out.println(city);<br>       redisTemplate.opsForValue().set(<span class="hljs-string">&quot;code&quot;</span>,<span class="hljs-string">&quot;1234&quot;</span>,<span class="hljs-number">3</span>, TimeUnit.MINUTES);<br>       redisTemplate.opsForValue().setIfAbsent(<span class="hljs-string">&quot;lock&quot;</span>,<span class="hljs-string">&quot;1&quot;</span>);<br>       redisTemplate.opsForValue().setIfAbsent(<span class="hljs-string">&quot;lock&quot;</span>,<span class="hljs-string">&quot;2&quot;</span>);<br>   &#125;<br></code></pre></td></tr></table></figure>



<p><strong>2). 操作哈希类型数据</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">    * 操作哈希类型的数据</span><br><span class="hljs-comment">    */</span><br>   <span class="hljs-meta">@Test</span><br>   <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">testHash</span><span class="hljs-params">()</span>&#123;<br>       <span class="hljs-comment">//hset hget hdel hkeys hvals</span><br>       <span class="hljs-type">HashOperations</span> <span class="hljs-variable">hashOperations</span> <span class="hljs-operator">=</span> redisTemplate.opsForHash();<br><br>       hashOperations.put(<span class="hljs-string">&quot;100&quot;</span>,<span class="hljs-string">&quot;name&quot;</span>,<span class="hljs-string">&quot;tom&quot;</span>);<br>       hashOperations.put(<span class="hljs-string">&quot;100&quot;</span>,<span class="hljs-string">&quot;age&quot;</span>,<span class="hljs-string">&quot;20&quot;</span>);<br><br>       <span class="hljs-type">String</span> <span class="hljs-variable">name</span> <span class="hljs-operator">=</span> (String) hashOperations.get(<span class="hljs-string">&quot;100&quot;</span>, <span class="hljs-string">&quot;name&quot;</span>);<br>       System.out.println(name);<br><br>       <span class="hljs-type">Set</span> <span class="hljs-variable">keys</span> <span class="hljs-operator">=</span> hashOperations.keys(<span class="hljs-string">&quot;100&quot;</span>);<br>       System.out.println(keys);<br><br>       <span class="hljs-type">List</span> <span class="hljs-variable">values</span> <span class="hljs-operator">=</span> hashOperations.values(<span class="hljs-string">&quot;100&quot;</span>);<br>       System.out.println(values);<br><br>       hashOperations.delete(<span class="hljs-string">&quot;100&quot;</span>,<span class="hljs-string">&quot;age&quot;</span>);<br>   &#125;<br></code></pre></td></tr></table></figure>



<p><strong>3). 操作列表类型数据</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">    * 操作列表类型的数据</span><br><span class="hljs-comment">    */</span><br>   <span class="hljs-meta">@Test</span><br>   <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">testList</span><span class="hljs-params">()</span>&#123;<br>       <span class="hljs-comment">//lpush lrange rpop llen</span><br>       <span class="hljs-type">ListOperations</span> <span class="hljs-variable">listOperations</span> <span class="hljs-operator">=</span> redisTemplate.opsForList();<br><br>       listOperations.leftPushAll(<span class="hljs-string">&quot;mylist&quot;</span>,<span class="hljs-string">&quot;a&quot;</span>,<span class="hljs-string">&quot;b&quot;</span>,<span class="hljs-string">&quot;c&quot;</span>);<br>       listOperations.leftPush(<span class="hljs-string">&quot;mylist&quot;</span>,<span class="hljs-string">&quot;d&quot;</span>);<br><br>       <span class="hljs-type">List</span> <span class="hljs-variable">mylist</span> <span class="hljs-operator">=</span> listOperations.range(<span class="hljs-string">&quot;mylist&quot;</span>, <span class="hljs-number">0</span>, -<span class="hljs-number">1</span>);<br>       System.out.println(mylist);<br><br>       listOperations.rightPop(<span class="hljs-string">&quot;mylist&quot;</span>);<br><br>       <span class="hljs-type">Long</span> <span class="hljs-variable">size</span> <span class="hljs-operator">=</span> listOperations.size(<span class="hljs-string">&quot;mylist&quot;</span>);<br>       System.out.println(size);<br>   &#125;<br></code></pre></td></tr></table></figure>



<p><strong>4). 操作集合类型数据</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">    * 操作集合类型的数据</span><br><span class="hljs-comment">    */</span><br>   <span class="hljs-meta">@Test</span><br>   <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">testSet</span><span class="hljs-params">()</span>&#123;<br>       <span class="hljs-comment">//sadd smembers scard sinter sunion srem</span><br>       <span class="hljs-type">SetOperations</span> <span class="hljs-variable">setOperations</span> <span class="hljs-operator">=</span> redisTemplate.opsForSet();<br><br>       setOperations.add(<span class="hljs-string">&quot;set1&quot;</span>,<span class="hljs-string">&quot;a&quot;</span>,<span class="hljs-string">&quot;b&quot;</span>,<span class="hljs-string">&quot;c&quot;</span>,<span class="hljs-string">&quot;d&quot;</span>);<br>       setOperations.add(<span class="hljs-string">&quot;set2&quot;</span>,<span class="hljs-string">&quot;a&quot;</span>,<span class="hljs-string">&quot;b&quot;</span>,<span class="hljs-string">&quot;x&quot;</span>,<span class="hljs-string">&quot;y&quot;</span>);<br><br>       <span class="hljs-type">Set</span> <span class="hljs-variable">members</span> <span class="hljs-operator">=</span> setOperations.members(<span class="hljs-string">&quot;set1&quot;</span>);<br>       System.out.println(members);<br><br>       <span class="hljs-type">Long</span> <span class="hljs-variable">size</span> <span class="hljs-operator">=</span> setOperations.size(<span class="hljs-string">&quot;set1&quot;</span>);<br>       System.out.println(size);<br><br>       <span class="hljs-type">Set</span> <span class="hljs-variable">intersect</span> <span class="hljs-operator">=</span> setOperations.intersect(<span class="hljs-string">&quot;set1&quot;</span>, <span class="hljs-string">&quot;set2&quot;</span>);<br>       System.out.println(intersect);<br><br>       <span class="hljs-type">Set</span> <span class="hljs-variable">union</span> <span class="hljs-operator">=</span> setOperations.union(<span class="hljs-string">&quot;set1&quot;</span>, <span class="hljs-string">&quot;set2&quot;</span>);<br>       System.out.println(union);<br><br>       setOperations.remove(<span class="hljs-string">&quot;set1&quot;</span>,<span class="hljs-string">&quot;a&quot;</span>,<span class="hljs-string">&quot;b&quot;</span>);<br>   &#125;<br></code></pre></td></tr></table></figure>



<p><strong>5). 操作有序集合类型数据</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">    * 操作有序集合类型的数据</span><br><span class="hljs-comment">    */</span><br>   <span class="hljs-meta">@Test</span><br>   <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">testZset</span><span class="hljs-params">()</span>&#123;<br>       <span class="hljs-comment">//zadd zrange zincrby zrem</span><br>       <span class="hljs-type">ZSetOperations</span> <span class="hljs-variable">zSetOperations</span> <span class="hljs-operator">=</span> redisTemplate.opsForZSet();<br><br>       zSetOperations.add(<span class="hljs-string">&quot;zset1&quot;</span>,<span class="hljs-string">&quot;a&quot;</span>,<span class="hljs-number">10</span>);<br>       zSetOperations.add(<span class="hljs-string">&quot;zset1&quot;</span>,<span class="hljs-string">&quot;b&quot;</span>,<span class="hljs-number">12</span>);<br>       zSetOperations.add(<span class="hljs-string">&quot;zset1&quot;</span>,<span class="hljs-string">&quot;c&quot;</span>,<span class="hljs-number">9</span>);<br><br>       <span class="hljs-type">Set</span> <span class="hljs-variable">zset1</span> <span class="hljs-operator">=</span> zSetOperations.range(<span class="hljs-string">&quot;zset1&quot;</span>, <span class="hljs-number">0</span>, -<span class="hljs-number">1</span>);<br>       System.out.println(zset1);<br><br>       zSetOperations.incrementScore(<span class="hljs-string">&quot;zset1&quot;</span>,<span class="hljs-string">&quot;c&quot;</span>,<span class="hljs-number">10</span>);<br><br>       zSetOperations.remove(<span class="hljs-string">&quot;zset1&quot;</span>,<span class="hljs-string">&quot;a&quot;</span>,<span class="hljs-string">&quot;b&quot;</span>);<br>   &#125;<br></code></pre></td></tr></table></figure>



<p><strong>6). 通用命令操作</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/**</span><br><span class="hljs-comment">    * 通用命令操作</span><br><span class="hljs-comment">    */</span><br>   <span class="hljs-meta">@Test</span><br>   <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">testCommon</span><span class="hljs-params">()</span>&#123;<br>       <span class="hljs-comment">//keys exists type del</span><br>       <span class="hljs-type">Set</span> <span class="hljs-variable">keys</span> <span class="hljs-operator">=</span> redisTemplate.keys(<span class="hljs-string">&quot;*&quot;</span>);<br>       System.out.println(keys);<br><br>       <span class="hljs-type">Boolean</span> <span class="hljs-variable">name</span> <span class="hljs-operator">=</span> redisTemplate.hasKey(<span class="hljs-string">&quot;name&quot;</span>);<br>       <span class="hljs-type">Boolean</span> <span class="hljs-variable">set1</span> <span class="hljs-operator">=</span> redisTemplate.hasKey(<span class="hljs-string">&quot;set1&quot;</span>);<br><br>       <span class="hljs-keyword">for</span> (Object key : keys) &#123;<br>           <span class="hljs-type">DataType</span> <span class="hljs-variable">type</span> <span class="hljs-operator">=</span> redisTemplate.type(key);<br>           System.out.println(type.name());<br>       &#125;<br><br>       redisTemplate.delete(<span class="hljs-string">&quot;mylist&quot;</span>);<br>   &#125;<br></code></pre></td></tr></table></figure>


                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/Redis/" class="category-chain-item">Redis</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/%E9%BB%91%E9%A9%AC/" class="print-no-link">#黑马</a>
      
        <a href="/tags/Redis/" class="print-no-link">#Redis</a>
      
        <a href="/tags/redis/" class="print-no-link">#redis</a>
      
        <a href="/tags/%E5%85%A5%E9%97%A8/" class="print-no-link">#入门</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>Redis入门</div>
      <div>https://xiazhimiao.gitee.io/2024/08/11/Redis入门/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>XiaZhiMiao</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2024年8月11日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a class="print-no-link" target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2024/08/02/knife4j-Swagger/" title="knife4j&lt;-Swagger">
                        <span class="hidden-mobile">knife4j&lt;-Swagger</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
  
  
    <article id="comments" lazyload>
      
  <div id="valine"></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#valine', function() {
      Fluid.utils.createScript('https://lib.baomitu.com/valine/1.5.1/Valine.min.js', function() {
        var options = Object.assign(
          {"appId":"Gwfs4a7ZrcziUqDRNGWYCyFE-gzGzoHsz","appKey":"EftcChyXDAcaoX5XepM4iOMI","path":"window.location.pathname","placeholder":null,"avatar":"retro","meta":["nick","mail","link"],"requiredFields":[],"pageSize":10,"lang":"zh-CN","highlight":false,"recordIP":false,"serverURLs":"","emojiCDN":null,"emojiMaps":null,"enableQQ":false},
          {
            el: "#valine",
            path: window.location.pathname
          }
        )
        new Valine(options);
        Fluid.utils.waitElementVisible('#valine .vcontent', () => {
          var imgSelector = '#valine .vcontent img:not(.vemoji)';
          Fluid.plugins.imageCaption(imgSelector);
          Fluid.plugins.fancyBox(imgSelector);
        })
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


    </article>
  


          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="leancloud-site-pv-container" style="display: none">
        总访问量 
        <span id="leancloud-site-pv"></span>
         次
      </span>
    
    
      <span id="leancloud-site-uv-container" style="display: none">
        总访客数 
        <span id="leancloud-site-uv"></span>
         人
      </span>
    
    

  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.4/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.20.1/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script defer src="/js/leancloud.js" ></script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
